package com.ruoyi.function.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.function.constant.BusinessConstants;
import com.ruoyi.function.domain.EncryptResource;
import com.ruoyi.function.domain.WeChatPaymentResponse;
import com.ruoyi.function.domain.WechatRefundNotification;
import com.ruoyi.function.domain.bo.OrdersBo;
import com.ruoyi.function.domain.bo.WechatPayCallbackBo;
import com.ruoyi.function.domain.vo.OrdersVo;
import com.ruoyi.message.controller.NoticeController;
import com.ruoyi.message.notice.vo.NoticeVO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.function.domain.Orders;
import com.ruoyi.function.service.IOrdersService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static org.hibernate.validator.internal.util.Contracts.assertNotNull;

/**
 * 订单Controller
 *
 * @author ruoyi
 * @date 2025-03-21
 */
@RestController
@RequestMapping("/function/orders")
public class OrdersController extends BaseController {
    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private NoticeController noticeController;

    /**
     * 查询订单列表
     */
//    @PreAuthorize("@ss.hasPermi('function:orders:list')")
    @GetMapping("/list")
    public TableDataInfo list(Orders orders) {
        startPage();
        List<OrdersVo> list = ordersService.selectOrdersVoList(orders);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('function:orders:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Orders orders) {
        List<Orders> list = ordersService.selectOrdersList(orders);
        ExcelUtil<Orders> util = new ExcelUtil<Orders>(Orders.class);
        util.exportExcel(response, list, "订单数据");
    }

    /**
     * 获取订单详细信息
     */
//    @PreAuthorize("@ss.hasPermi('function:orders:query')")
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId) {
        return success(ordersService.selectOrdersByOrderId(orderId));
    }

    /**
     * 新增订单
     */
    @PreAuthorize("@ss.hasPermi('function:orders:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Orders orders) {
        return toAjax(ordersService.insertOrders(orders));
    }

    /**
     * 小程序新增订单
     */
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/addOrderApp")
    public AjaxResult addApp(@RequestBody OrdersBo ordersBo) {
        return success(ordersService.addOrderApp(ordersBo));
    }



    /**
     * 小程序订单操作
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/orderApp")
    public AjaxResult orderApp(@RequestBody OrdersBo ordersBo) {
        return toAjax(ordersService.orderApp(ordersBo));
    }

    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('function:orders:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Orders orders) {
        return toAjax(ordersService.updateOrders(orders));
    }

    /**
     * 删除订单
     */
    @PreAuthorize("@ss.hasPermi('function:orders:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable Long[] orderIds) {
        return toAjax(ordersService.deleteOrdersByOrderIds(orderIds));
    }

    /**
     * 获取我的订单
     */
    @GetMapping("/myOrders")
    public TableDataInfo myOrders(Orders orders) {

        List<OrdersVo> list = ordersService.myOrders(orders);
        return getDataTable(list);
    }
    /**
     * 用户获取我的订单
     */
    @GetMapping("/usersMyOrders")
    public TableDataInfo usersMyOrders(Orders orders) {

        List<OrdersVo> list = ordersService.usersMyOrders(orders);
        return getDataTable(list);
    }


    /**
     * 订单支付成功修改订单状态
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/paymentSuccess")
    public AjaxResult paymentSuccess(@RequestBody WechatPayCallbackBo wechatPayCallbackBo) {

        logger.info("支付成功回调data{}",wechatPayCallbackBo);
        try {
            WechatPayCallbackBo.Resource resource = wechatPayCallbackBo.getResource();
            if (resource == null) {
                return error("支付失败");
            }
            String outTradeNo = resource.getOutTradeNo();
            String tradeState = resource.getTradeState();
            if (!tradeState.equals("SUCCESS")) {
                return error("支付失败");
            }
            Orders orders1 = ordersService.selectOrdersByOrderId(Long.parseLong(outTradeNo));
            if (orders1 == null) {
                return error("支付失败,订单不存在");
            }
            if (!orders1.getOrderStatus().equals("0")){
                //发送消息
                NoticeVO noticeVO = new NoticeVO();
                noticeVO.setReceiverId(orders1.getOrdersUser() + "");
                noticeVO.setMessageContent(BusinessConstants.message_1);
                noticeVO.setUserType(orders1.getReceivingType());
                noticeController.add(noticeVO);
                orders1.setOrderStatus("1");
                ordersService.updateOrderStatus(orders1);
            }
            return success("{\"code\":\"SUCCESS\",\"message\":\"OK\"}");
        } catch (Exception e) {
            e.printStackTrace();
            // 如果处理失败，返回错误信息
            return success("{\"code\":\"FAIL\",\"message\":\"Server Error\"}");
        }
    }


    /**
     * 小程序修改订单状态
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/updateOrderStatusApp")
    public AjaxResult updateOrderStatusApp(@RequestBody Orders orders) {
        return toAjax(ordersService.updateOrderStatus(orders));
    }

    /**
     * 订单评分
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/evaluation")
    public AjaxResult evaluation(@RequestBody Orders orders) {
        return toAjax(ordersService.evaluation(orders));
    }


    /**
     * 退款回调
     */
    @PostMapping("/refundCallback")
    public AjaxResult refundCallback(@RequestBody WechatRefundNotification wechatRefundNotification) {
        logger.info("退款回调成功data{}",wechatRefundNotification);
        try {
            EncryptResource resource = wechatRefundNotification.getResource();
            if (resource == null) {
                return error("退款失败");
            }
            String outTradeNo = resource.getOutTradeNo();
            String tradeState = resource.getRefundStatus();
            if (!tradeState.equals("SUCCESS")) {
                return error("退款失败");
            }
            Orders orders1 = ordersService.selectOrdersByOrderId(Long.parseLong(outTradeNo));
            if (orders1 == null) {
                return error("退款失败,订单不存在");
            }
            if (!orders1.getOrderStatus().equals("3")){
                //发送消息
                NoticeVO noticeVO = new NoticeVO();
                noticeVO.setReceiverId(orders1.getUserId() + "");
                noticeVO.setMessageContent(BusinessConstants.message_3);
                noticeVO.setUserType(orders1.getReceivingType());
                noticeController.add(noticeVO);
                orders1.setOrderStatus("4");
                ordersService.updateOrderStatus(orders1);
            }

            return success("{\"code\":\"SUCCESS\",\"message\":\"OK\"}");
        } catch (Exception e) {
            e.printStackTrace();
            // 如果处理失败，返回错误信息
            return success("{\"code\":\"FAIL\",\"message\":\"Server Error\"}");
        }
    }


    /**
     * 取消订单
     * @param orders
     * @return
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/cancelOrder")
    public AjaxResult cancelOrder(@RequestBody Orders orders) {
        return toAjax(ordersService.cancelOrder(orders));
    }




    /**
     * 新增子订单
     * @param ordersBo
     * @return
     */
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/addSubOrder")
    public AjaxResult addSubOrder(@RequestBody OrdersBo ordersBo) {

        return toAjax(ordersService.addSubOrder(ordersBo));
    }


}
